<template>
  <div class="product-specification">
    <el-card>
      <PageTools :btn-close-show="true" @addBtn="addOrEditBtn" @deleteBtn="deleteBtn" @resetBtn="resetFn" />
      <el-table
        v-if="tableData"
        ref="multipleTable"
        v-loading="loading"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="selectChange"
      >
        <el-table-column type="selection" width="60" align="center" />
        <el-table-column prop="name" label="规格名称" width="150" />
        <el-table-column prop="default" label="规格值" width="250" />
        <el-table-column prop="order" label="排序" width="150" align="center" />
        <el-table-column prop="status" label="状态" width="150" align="center">
          <template slot-scope="{row}">
            <el-switch v-model="row.status" @change="updateSkuStatus(row.id,row.status)" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="right">
          <template slot-scope="{row}">
            <el-row type="flex" justify="end">
              <el-col :span="4">
                <el-button type="text" size="small" @click="addOrEditBtn(row)">修改</el-button>
              </el-col>
              <el-col :span="4">
                <template>
                  <el-popconfirm confirm-button-text="是" cancel-button-text="否" title="是否要删除批量删除选中？" @confirm="deleteBtn(row.id)">
                    <el-button slot="reference" type="text" size="small">删除</el-button>
                  </el-popconfirm>
                </template>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-row class="pagination" type="flex" justify="center">
        <el-pagination background layout="prev, pager, next" :total="params.totalCount" @current-change="pageChange" />
      </el-row>
    </el-card>

    <!-- 弹层 -->
    <el-dialog
      v-if="formData"
      :visible="dialogShow"
      :title="formData.id != null ? '修改' : '新增'"
      top="0"
      @close="BtnClose"
    >
      <div class="center">
        <el-form ref="form" :model="formData" :rules="formRules" label-width="80px">
          <el-form-item label="规格名称" prop="name">
            <el-input v-model="formData.name" size="small" />
          </el-form-item>
          <el-form-item label="排序">
            <el-input-number v-model="formData.order" :min="0" size="mini" />
          </el-form-item>
          <el-form-item label="状态">
            <el-switch v-model="formData.status" />
          </el-form-item>
          <el-form-item label="规格值" prop="default" class="tag-wrap">
            <!-- tag添加组件 -->
            <GoodsSkusTag :data="formData.default" :add-tag-show.sync="addTagShow" @blurFn="blurFn" @deleteTagBtn="deleteTagBtn" />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" size="small" @click="BtnOk(formData.id)">确认</el-button>
          <el-button size="small" @click="BtnClose">取消</el-button>
        </span>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getSkuList, addSku, updateSku, deleteSku, updateSkuStatus } from '@/api/skus'
const tagValidate = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请填写规格'))
  }
  callback()
}
export default {
  name: 'ProductSpecification',
  data() {
    return {
      // 表格数据
      tableData: null,
      params: {
        page: 1, // 页码
        totalCount: null // 数据总数
      },
      deleteParams: {
        ids: null
      },
      dialogShow: false, // 弹层显示
      // 弹层数据，校验
      formData: {
        status: true, // 状态
        name: '', // 规格名
        order: 100, // 排序
        default: '' // 规格值
      },
      formRules: {
        name: [{ required: true, message: '规格名不能为空', trigget: 'blur' }],
        default: [{ validator: tagValidate, trigget: 'blur' }]
      },
      loading: false,
      tag: '', // 添加tag输入框
      addTagShow: true // 控制添加tag按钮和输入框显示隐藏
    }
  },
  created() {
    this.getSkuList()
  },
  methods: {
    async getSkuList() {
      try {
        this.loading = true
        const { list, totalCount } = await getSkuList(this.params.page)
        list.forEach(obj => {
          if (obj.status === '1') {
            obj.status = true
          } else {
            obj.status = false
          }
        })
        this.tableData = list
        this.params.totalCount = totalCount
      } catch (error) {
        console.log(error)
      } finally {
        this.loading = false
      }
    },
    // 点击check触发
    selectChange(val) {
      const ids = []
      val.forEach(obj => {
        ids.push(obj.id)
      })
      this.deleteParams.ids = ids
    },
    // 公共组件刷新按钮方法
    resetFn() {
      console.log('刷新')
    },
    // 打开新增/编辑弹层
    addOrEditBtn(data) {
      this.dialogShow = true
      if (data) {
        // 修改
        this.formData = data
        this.formData.default = this.formData.default.split(',')
      }
    },
    // 批量删除功能
    async deleteBtn(id) {
      if (id) {
        // 单个删除
        this.deleteParams.ids = [id]
      }
      try {
        await deleteSku(this.deleteParams.ids)
        this.getSkuList()
        this.$message.success('删除规格成功')
      } catch (error) {
        console.log(error)
      }
    },
    // 弹层取消确定按钮
    BtnClose() {
      this.dialogShow = false
      this.formData = {
        status: true, // 状态
        name: '', // 规格名
        order: 100, // 排序
        default: '' // 规格值
      }
      this.$refs.form.resetFields()
      this.getSkuList()
    },
    BtnOk(id) {
      this.$refs.form.validate(async isOk => {
        const data = this.getApiData()
        if (isOk) {
          try {
            if (!id) {
              // 新增
              await addSku(data)
              this.getSkuList()
              this.$message.success('新增规格成功')
            } else {
              // 编辑
              await updateSku(data, id)
              this.getSkuList()
              this.$message.success('修改规格成功')
            }
            this.BtnClose()
          } catch (error) {
            console.log(error)
          }
        } else {
          return false
        }
      })
    },
    // 规格值输入框
    blurFn(tag) {
      this.tag = tag
      this.addTagShow = true
      let tagName = this.formData.default

      if (tagName === '') {
        tagName += this.tag
      } else {
        tagName += ',' + this.tag
      }
      if (this.tag) {
        this.formData.default = tagName.split(',')
      }
      this.tag = ''
    },
    deleteTagBtn(index) {
      console.log(this.formData.default)
      this.formData.default.splice(index, 1)
    },
    // 分页功能
    pageChange(page) {
      this.params.page = page
      this.getSkuList()
    },
    // 修改规格状态
    async updateSkuStatus(id, state) {
      let status = null
      if (state === true) {
        status = 1
      } else {
        status = 0
      }
      try {
        console.log(id, status)
        await updateSkuStatus(id, status)
      } catch (error) {
        console.log(error)
      }
    },
    // 获取api参数封装
    getApiData() {
      const data = {
        status: this.formData.status, // 状态
        name: this.formData.name, // 规格名
        order: this.formData.order, // 排序
        default: this.formData.default // 规格值
      }
      for (const key in data) {
        if (data[key] === true) {
          data[key] = 1
        } else if (data[key] === false) {
          data[key] = 0
        }
        if (Array.isArray(data[key])) {
          data[key] = data[key].join()
        }
      }
      return data
    }
  }

}
</script>
<style lang="scss" scoped>
.product-specification {

  .center {

    ::v-deep .el-form-item.tag-wrap {
      display: flex;
      align-items: center;

      .el-form-item__content {
        margin: 0 !important;
      }
    }

  }
}
</style>

